package com.changhong.wlyspectrum.RegisterActivity;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.changhong.wlyspectrum.HttpUtil.HttpFunc;
import com.changhong.wlyspectrum.NetWork.HttpMethods;
import com.changhong.wlyspectrum.R;
import com.changhong.wlyspectrum.utils.MyConfig;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

/**
 * Created by Mr_tao
 * on 2017/3/7.
 */
public class RegisterActivity extends Activity {
    private final static String TAG = "RegisterActivity";
    private ImageView mBackImv;
    private EditText mWorkShopIdEdt;
    private EditText mGroupIdEdt;
    private EditText mDeviceIdEdt;
    private EditText u_name;
    private EditText mPhoneNumEdt;
    private EditText mPassWordEdt;
    private EditText mVerifyCodeEdt;
    private Button mGetCodeBtn;
    private Button mNextBtn;
    private String mWorkShopId = "0";
    private String mGroupId = "0";
    private String mDeviceId ="0";
    private String user_name;
    private String mPhoneNum;
    private String mPassWord;
    private String mVerifyCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_layout);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar_register);

        InitUi();
    }

    private void InitUi() {
        mBackImv = (ImageView) findViewById(R.id.reg2login);
        mBackImv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        u_name = (EditText)findViewById(R.id.u_name);
        u_name.setOnFocusChangeListener(new View.OnFocusChangeListener(){
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    u_name.setHint(null);
                } else {
                    if (u_name.getText().length() != 0) {
                        u_name.setHint(null);
                    } else {
                        u_name.setHint(R.string.input_user_name);
                    }
                }

            }

        });

        mPhoneNumEdt = (EditText) findViewById(R.id.phoneNum);
        mPhoneNumEdt.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mPhoneNumEdt.setHint(null);
                } else {
                    if (mPhoneNumEdt.getText().length() != 0) {
                        mPhoneNumEdt.setHint(null);
                    } else {
                        mPhoneNumEdt.setHint(R.string.input_user_phone);
                    }
                }

            }
        });
        mPhoneNumEdt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mPhoneNumEdt.getText().length() != 0) {
                    mPhoneNumEdt.setHint(null);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mPassWordEdt = (EditText) findViewById(R.id.passwordNum);
        mPassWordEdt.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mPassWordEdt.setHint(null);
                } else {
                    if (mPassWordEdt.getText().length() != 0) {
                        mPassWordEdt.setHint(null);
                    } else {
                        mPassWordEdt.setHint(R.string.input_pwd);
                    }
                }

            }
        });
        mPassWordEdt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mPassWordEdt.getText().length() != 0) {
                    mPassWordEdt.setHint(null);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mVerifyCodeEdt = (EditText) findViewById(R.id.verifyCode);
        mVerifyCodeEdt.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mVerifyCodeEdt.setHint(null);
                } else {
                    if (mVerifyCodeEdt.getText().length() != 0) {
                        mVerifyCodeEdt.setHint(null);
                    } else {
                        mVerifyCodeEdt.setHint(R.string.input_verify);
                    }
                }

            }
        });
        mVerifyCodeEdt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mVerifyCodeEdt.getText().length() != 0) {
                    mVerifyCodeEdt.setHint(null);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mGetCodeBtn = (Button) findViewById(R.id.verify_btn);
        mGetCodeBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mPhoneNum = mPhoneNumEdt.getText().toString();
                //Log.e(TAG,"mphoneNum:"+mPhoneNum+",length:"+mPhoneNum.length());
                if (MyConfig.isMobile(mPhoneNum)) {
                    Log.e(TAG, "get verify code");
                    GetCode(mPhoneNum);
                    mGetCodeBtn.setEnabled(false);
                } else {
                    Toast.makeText(getApplicationContext(), R.string.input_correct_phone, Toast.LENGTH_SHORT).show();
                }
            }
        });

        mNextBtn = (Button) findViewById(R.id.next_btn);
        mNextBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                user_name = u_name.getText().toString();
                mPhoneNum = mPhoneNumEdt.getText().toString();
                mPassWord = mPassWordEdt.getText().toString();
                mVerifyCode = mVerifyCodeEdt.getText().toString();
                if(!mPhoneNum.isEmpty()){
                    if(!mPassWord.isEmpty()){
                        if(!mVerifyCode.isEmpty()){
                            Register(user_name,mPassWord,mVerifyCode,"1",mPhoneNum);
                            mNextBtn.setEnabled(false);
                        }else{
                            Toast.makeText(getApplicationContext(),
                                    R.string.input_verify, Toast.LENGTH_LONG).show();
                        }
                    }else{
                        Toast.makeText(getApplicationContext(),
                                R.string.input_pwd, Toast.LENGTH_LONG).show();
                    }
                }else{
                    Toast.makeText(getApplicationContext(),
                            R.string.input_phone, Toast.LENGTH_LONG).show();
                }

            }
        });

    }

    private Handler registerHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(getApplicationContext(),
                            R.string.send_message, Toast.LENGTH_LONG).show();
                    mGetCodeBtn.setEnabled(true);
                    break;
                case 1:
                    Log.e(TAG, "verify_code ok");
                    //new RegisterThread(mPhoneNum, mVerifyCode, mPassWord, mWorkShopId, mGroupId, mDeviceId).start();
                    //Register(mPhoneNum, mVerifyCode, mPassWord, mWorkShopId, mGroupId, mDeviceId);
                    break;
                case 2:
                    Toast.makeText(getApplicationContext(),
                            R.string.verify_error, Toast.LENGTH_LONG).show();
                    mNextBtn.setEnabled(true);
                    break;
                case 3:
                    Toast.makeText(getApplicationContext(),
                            R.string.register_ok, Toast.LENGTH_LONG).show();
                    mNextBtn.setEnabled(true);
                    finish();
                    break;
                case 4:
                   // Toast.makeText(getApplicationContext(),
                       //     R.string.register_fail, Toast.LENGTH_LONG).show();
                    String mes = (String)msg.obj;
                    Toast.makeText(getApplicationContext(),mes, Toast.LENGTH_LONG).show();
                    mNextBtn.setEnabled(true);
                    break;
                case 5:
                    Toast.makeText(getApplicationContext(),
                            R.string.registed, Toast.LENGTH_LONG).show();
                    mNextBtn.setEnabled(true);
                    finish();
                    break;
                case 98:
                    Toast.makeText(getApplicationContext(),
                            R.string.verify_fail, Toast.LENGTH_LONG).show();
                    mGetCodeBtn.setEnabled(true);
                    break;
                case 99:
                    Toast.makeText(getApplicationContext(),
                            R.string.network_error, Toast.LENGTH_LONG).show();
                    mGetCodeBtn.setEnabled(true);
                    mNextBtn.setEnabled(true);
                    break;
                default:
                    break;
            }
        }
    };

    private void GetCode(final String phonenum){
        new Thread(){
            @Override
            public void run() {
                super.run();
                JSONObject js = new JSONObject();
                try {
                    js.put("phone",phonenum);
                    Response response = HttpFunc.getInstance().GetResponse("/user/phonecode/",js.toString());
                    //Log.e(TAG,response.toString());
                    if(response.isSuccessful()){
                        registerHandler.sendMessage(Message.obtain(registerHandler, 0));
                    }else{
                        registerHandler.sendMessage(Message.obtain(registerHandler, 98));
                    }
                } catch (JSONException e) {
                    registerHandler.sendMessage(Message.obtain(registerHandler, 99));
                    e.printStackTrace();
                } catch (IOException e) {
                    registerHandler.sendMessage(Message.obtain(registerHandler, 99));
                    e.printStackTrace();
                }
            }
        }.start();
    }


    private void Register(final String username, final String password, final String verifycode,
                          final String organization, final String mphone){
        new Thread(){
            @Override
            public void run() {
                super.run();
                JSONObject js = new JSONObject();
                try{
                    js.put("username",username);
                    js.put("password",password);
                    js.put("code",verifycode);
                    js.put("organization",organization);
                    js.put("phone",mphone);
                    Response response = HttpFunc.getInstance().GetResponse("/user/regist/",js.toString());
                    String str = response.body().string();
                    JSONObject obj = new JSONObject(str);
                    String message = obj.getString("message");
                    if(response.isSuccessful()){
                        SharedPreferences mypref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                        SharedPreferences.Editor editor = mypref.edit();
                        editor.putString("username", mphone);
                        editor.putString("password", password);
                        editor.commit();
                        registerHandler.sendMessage(Message.obtain(registerHandler, 3));
                    }else{
                        registerHandler.sendMessage(Message.obtain(registerHandler, 4, message));
                    }
                } catch (JSONException e) {
                    registerHandler.sendMessage(Message.obtain(registerHandler, 99));
                    e.printStackTrace();
                } catch (IOException e) {
                    registerHandler.sendMessage(Message.obtain(registerHandler, 99));
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
